﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mshtml;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using Intorise.API;
using Intorise.Framework;

namespace Intorise.Common
{
    public class WebBrowserTools
    {
        private static Security security = null;

        public static void DisableAlert(WebBrowser browser)
        {
            IHTMLWindow2 win = (IHTMLWindow2)browser.Document.Window.DomWindow;
            string s = "window.alert = null;\r\nwindow.confirm = null;\r\nwindow.open = null;\r\nwindow.showModalDialog = null;";
            win.execScript(s, "javascript");
        }

        public static void SaveImg(WebBrowser browser, string imgID, string fullFilename)
        {
            IHTMLDocument2 doc = (IHTMLDocument2)browser.Document.DomDocument;
            IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();

            IHTMLImgElement img = (IHTMLImgElement)browser.Document.GetElementById(imgID).DomElement;
            imgRange.add((IHTMLControlElement)img);
            imgRange.execCommand("Copy", false, null);
            using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
            {
                bmp.Save(fullFilename, ImageFormat.Jpeg);
            }
        }

        public static void ClearCookie(WebBrowser browser)
        {
            browser.Navigate("javascript:void((function(){var a,b,c,e,f;f=0;a=document.cookie.split('; ');for(e=0;e<a.length&&a[e];e++){f++;for(b='.'+location.host;b;b=b.replace(/^(?:%5C.|[^%5C.]+)/,'')){for(c=location.pathname;c;c=c.replace(/.$/,'')){document.cookie=(a[e]+'; domain='+b+'; path='+c+'; expires='+new Date((new Date()).getTime()-1e11).toGMTString());}}}})())");
        }

        public static void SetCookie(HttpWebResponse response)
        {
            foreach (Cookie cookie in response.Cookies)
            {
                Windows.InternetSetCookie(cookie.Domain, cookie.Name, cookie.Value);
            }
        }

        public static void SetCookie(CookieCollection cookies)
        {
            foreach (Cookie cookie in cookies)
            {
                Windows.InternetSetCookie(cookie.Domain, cookie.Name, cookie.Value);
            }
        }
    }
}
